import { Component } from "react";
import './App.css'
import Header from "./component/Header";
import Item from './component/Item'
import Bottom from "./component/Bottom";
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      allCheck: false
    }
  }
  addObj(e){
    // console.log(e);
    let obj = {
      check:false,
      title:e,
      id:new Date().getTime()
    }

    this.state.list.push(obj)
    this.setState({
      list: this.state.list
    })
  }
  change(id, b) {
    const index = this.state.list.findIndex(item => item.id === id)
    // if(b)  {
    //   this.state.list[index].check = !this.state.list[index].check
    // } else {
    //     this.state.list.splice(index,1)
    // }
    b ? this.state.list[index].check = !this.state.list[index].check : this.state.list.splice(index,1)
    this.setState({
      list:this.state.list
    })
    this.state.allCheck = this.state.list.every(item => item.check)
    this.setState({
      allCheck: this.state.allCheck
    })
  }
  // 全选
  allChangeCks(b) {
    this.state.list.forEach(item => {
      item.check = b
    })
    this.setState({
      list: this.state.list,
      allCheck: b
    })
  }
  // 选中删除
  choseDel() {
    this.state.list = this.state.list.filter(item => !item.check)
    this.setState({
      list: this.state.list
    })
    // console.log(this.state.list.length)
    if(this.state.list.length === 0) {
      this.setState({
        allCheck: false
      })
    }
  }
  render() {
    return (
      <div className="app">
        <Header addObj={this.addObj.bind(this)} />
        <Item list={this.state.list} change={this.change.bind(this)} />
        <Bottom list={ this.state.list } allCheck={ this.state.allCheck } choseDel={ this.choseDel.bind(this) } allChangeCks={ this.allChangeCks.bind(this) } />
      </div>
    );
  }
}
